<?php
/**
 * Created by PhpStorm.
 * User: xing.chen
 * Date: 2017/8/26
 * Time: 7:12
 */

namespace common\service;

use Yii;

class CacheService
{

    public static $prefix = '';
    protected static $cacheTime = 3600;
    protected static $dayOn = false; // 日开关，开了之后键名将会加入当天的号数（缓存时间会自动计算）

    /**
     * 返回单例
     * @return \yii\caching\Cache
     */
    public static function instance()
    {
        return Yii::$app->cache;
    }

    /**
     * 返回key
     * @param $name
     * @return string
     */
    public static function key($name)
    {
        return static::$prefix . $name;
    }

    /**
     * 保存token
     * @param $name
     * @param $value
     * @param null $expireTime
     * @return mixed
     */
    public static function set($name, $value, $expireTime = null)
    {
        return static::instance()->set(self::key($name), $value, static::getExpireTime($expireTime));
    }

    /**
     * 读取token
     * @param $name
     * @return mixed
     */
    public static function get($name)
    {
        return static::instance()->get(self::key($name));
    }

    /**
     * 删除
     * @param $name
     * @return bool
     */
    public static function del($name)
    {
        return static::instance()->delete(self::key($name));
    }

    /**
     * 获取当天剩余时间
     * @return false|int
     */
    protected static function getDaySurplusTime()
    {
        return strtotime(date('Y-m-d')) + 86400 - time();
    }

    /**
     * 获取过期时间
     * @param null $expireTime
     * @return false|int|null
     */
    private static function getExpireTime($expireTime = null)
    {
        if (!is_null($expireTime)) return $expireTime;
        return static::$dayOn ? static::getDaySurplusTime() : static::$cacheTime;
    }
}